<template>
  <div class="search-suggestion">
    <van-cell
    icon="search"
    v-for="(str, index) in suggestions"
    :key="index"
    @click="$emit('search', str)"
    >
    <div slot="title" v-html="highlight(str)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestion } from '@/api/search'
import { debounce } from 'lodash'

export default {
  name: 'SearchSuggestion',
  props: {
    searchText: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      suggestions: []
    }
  },
  watch: {
    // 属性名 要监视的数据名称
    // searchText () {
    //   console.log('hello')
    // }
    searchText: {
      handler: debounce(async function () {
        const { data } = await getSearchSuggestion(this.searchText)
        this.suggestions = data.data.options
      }, 200),
      // async handler () {
      // 找到数据接口
      // 请求获取数据
      // 模板绑定显示
      //   const { data } = await getSearchSuggestion(this.searchText)
      //   this.suggestions = data.data.options
      // },
      immediate: true
    }
  },
  mounted () {

  },
  methods: {
    highlight (str) {
      return str.replace(new RegExp(this.searchText, 'gi'),
      `<span style="color: red;">${this.searchText}</span>`)
    }
  }
}
</script>

<style lang="less" scoped>

</style>
